package miku.firstgame.view
{
	import com.saia.starlingPunk.SP;

	import flash.geom.Point;
	import flash.media.Video;

	import feathers.data.ListCollection;

	import miku.firstgame.constrants.AppConstrants;
	import miku.firstgame.constrants.EventConstants;
	import miku.firstgame.entity.Bomb;
	import miku.firstgame.model.Me;
	import miku.firstgame.model.User;
	import miku.firstgame.model.gold.CardPlaceVo;
	import miku.firstgame.model.gold.ToolPlaceVo;
	import miku.firstgame.model.gold.card.BombCard;
	import miku.firstgame.model.gold.card.GoldCardType;
	import miku.firstgame.model.gold.card.MapCard;
	import miku.firstgame.model.gold.card.RoadCard;
	import miku.firstgame.model.gold.card.ToolCard;
	import miku.firstgame.model.gold.util.CardUtil;
	import miku.firstgame.model.proxy.ProxyHelper;
	import miku.firstgame.model.vo.TalkVo;
	import miku.firstgame.net.pack.ExitRoomRequestPack;
	import miku.firstgame.net.pack.GetReadyRequestPack;
	import miku.firstgame.net.pack.GoldCompleteRequestPack;
	import miku.firstgame.net.pack.GoldCompleteResponsePack;
	import miku.firstgame.net.pack.SendUserACardResponsePack;
	import miku.firstgame.net.pack.SetRoadCardRequestPack;
	import miku.firstgame.net.pack.SetRoadCardResponsePack;
	import miku.firstgame.net.pack.SetToolToUserRequestPack;
	import miku.firstgame.net.pack.SetToolToUserResponsePack;
	import miku.firstgame.net.pack.TalkRequestPack;
	import miku.firstgame.net.pack.UserDropACardRequestPack;
	import miku.firstgame.ui.card.CardMap;
	import miku.firstgame.ui.card.CardUI;
	import miku.firstgame.ui.card.EndCardUI;
	import miku.firstgame.ui.card.RoadCardUI;
	import miku.firstgame.ui.card.UserSeat;
	import miku.firstgame.world.GameRoomWorld;
	import miku.firstgame.world.RoomWorld;

	import org.puremvc.as3.interfaces.INotification;
	import org.puremvc.as3.patterns.mediator.Mediator;

	import starling.events.Event;

	public class GameRoomWorldMediator extends Mediator
	{
		public static const NAME:String = "gameWorldMediator";

		private var gameRoomWorld:GameRoomWorld;

		public function GameRoomWorldMediator(viewComponent:Object = null)
		{
			super(NAME, viewComponent);
			this.gameRoomWorld = viewComponent as GameRoomWorld;
		}

		override public function onRegister():void
		{
			super.onRegister();
			gameRoomWorld.startGameButton.addEventListener(Event.TRIGGERED, onStartGameButtonClick);
			gameRoomWorld.exitRoomButton.addEventListener(Event.TRIGGERED, onExitRoomButtonClick);
			gameRoomWorld.messagePanel.addEventListener(EventConstants.LOBBY_MESSAGE_SEND, onMessageSend);
			gameRoomWorld.addEventListener(EventConstants.CARD_PLACE_ON_MAP, onCardPlaceOnMap);
			gameRoomWorld.addEventListener(EventConstants.USE_TOOL_ON_USER, onUseToolOnUser);
			gameRoomWorld.addEventListener(EventConstants.USER_DROP_A_CARD, onUserDropACard);
			initUserListSource();

		}

		override public function onRemove():void
		{
			super.onRemove();
			gameRoomWorld.startGameButton.removeEventListener(Event.TRIGGERED, onStartGameButtonClick);
			gameRoomWorld.exitRoomButton.removeEventListener(Event.TRIGGERED, onExitRoomButtonClick);
			gameRoomWorld.messagePanel.removeEventListener(EventConstants.LOBBY_MESSAGE_SEND, onMessageSend);
			gameRoomWorld.removeEventListener(EventConstants.CARD_PLACE_ON_MAP, onCardPlaceOnMap);
			gameRoomWorld.removeEventListener(EventConstants.USE_TOOL_ON_USER, onUseToolOnUser);
			gameRoomWorld.removeEventListener(EventConstants.USER_DROP_A_CARD, onUserDropACard);
		}

		//TODO 当卡牌对个人使用的时候
		private function onUseToolOnUser(e:Event):void
		{
			var tvo:ToolPlaceVo = e.data as ToolPlaceVo;
			gameRoomWorld.remove(tvo.tool);

			var pack:SetToolToUserRequestPack = new SetToolToUserRequestPack();
			pack.cardId = tvo.tool.card.type;
			pack.userId = tvo.userSeat.user.id;
			ProxyHelper.send(pack);

		}

		//TODO 当卡片放下的时候做的操作
		private function onCardPlaceOnMap(e:Event):void
		{
			var cvo:CardPlaceVo = e.data as CardPlaceVo;
			var map:CardMap = gameRoomWorld.cardMap;
			gameRoomWorld.remove(cvo.card);
			//gameRoomWorld.updateLists();
			if (cvo.card is RoadCardUI)
			{
				var pack:SetRoadCardRequestPack = new SetRoadCardRequestPack();
				pack.cardType = cvo.card.card.type;
				pack.x = cvo.position.x;
				pack.y = cvo.position.y;
				pack.togged = (cvo.card as RoadCardUI).toggled;
				ProxyHelper.send(pack);

				map.setCardPosition(cvo.card.card as RoadCard, cvo.position.x, cvo.position.y);

				var result:int = map.reached();
				if (result != -1)
				{
					var cPack:GoldCompleteRequestPack = new GoldCompleteRequestPack();
					cPack.result = result;
					ProxyHelper.send(cPack);
				}
			}
			else if (cvo.card.card is BombCard || cvo.card.card is MapCard) //TODO 炸弹卡，地图卡
			{
				var pack2:SetRoadCardRequestPack = new SetRoadCardRequestPack();
				pack2.cardType = cvo.card.card.type;
				pack2.x = cvo.position.x;
				pack2.y = cvo.position.y;
				pack2.togged = false;
				ProxyHelper.send(pack2);
			}
		}

		/**
		 *用户丢弃一张卡
		 * */
		private function onUserDropACard(e:Event):void
		{
			var card:CardUI = e.data as CardUI;
			var pack:UserDropACardRequestPack = new UserDropACardRequestPack();
			pack.cardId = card.card.type;
			ProxyHelper.send(pack);

			gameRoomWorld.remove(card);
		}

		private function initUserListSource():void
		{
			gameRoomWorld.userList.dataProvider = new ListCollection(Me.Instace.getContactUsers());
		}

		private function onMessageSend(e:Event):void
		{
			var pack:TalkRequestPack = new TalkRequestPack();
			pack.message = e.data.toString();
			pack.roomId = gameRoomWorld.room.roomId;
			pack.userId = Me.Instace.id;
//			var talkXml:XML = <t/>;
//			talkXml.@m = e.data.toString();
//			talkXml.@r = gameRoomWorld.room.roomId;
//			talkXml.@uid = Me.Instace.id;
			ProxyHelper.send(pack);
		}

		private function onStartGameButtonClick(e:Event):void
		{
			gameRoomWorld.startGameButton.isEnabled = false;

			var pack:GetReadyRequestPack = new GetReadyRequestPack();
			pack.isReady = !Me.Instace.isReady;
			ProxyHelper.send(pack);

		}

		private function onGetReadyFail():void
		{
			gameRoomWorld.startGameButton.isEnabled = true;
		}

//todo 界面上的准备取消.还有每个人的准备状态
		private function onUserGetReady(user:User):void
		{
			gameRoomWorld.userList.updateItem(user);
			gameRoomWorld.checkStartButton();
		}

///<xr id=""/>
		private function onExitRoomButtonClick(e:Event):void
		{
			//退出房间

			var pack:ExitRoomRequestPack = new ExitRoomRequestPack();
			pack.roomId = gameRoomWorld.room.roomId;
			ProxyHelper.send(pack);

			gameRoomWorld.exitRoomButton.isEnabled = false;
			gameRoomWorld.startGameButton.isEnabled = false;
		}

		private function onExitRoomSuccess():void
		{
			SP.world = new RoomWorld();
		}

		/**
		 * TODO 退出房间失败
		*/
		private function onExitRoomFail():void
		{
			gameRoomWorld.exitRoomButton.isEnabled = true;
			gameRoomWorld.startGameButton.isEnabled = true;
		}

		private function onReceiveLobbyMessage(talkVo:TalkVo):void
		{
			if (gameRoomWorld.room.roomId == talkVo.roomId)
			{
				gameRoomWorld.messagePanel.appendMessage(talkVo.user.name, talkVo.message);
			}
		}

		private function onUserEnterRoom(user:User):void
		{
			gameRoomWorld.messagePanel.appendSysMessage(user.name + " 进入了房间。");
			gameRoomWorld.userList.listCountChanged();
			gameRoomWorld.checkStartButton();
		}

		private function onUserExitRoom(user:User):void
		{
			gameRoomWorld.messagePanel.appendSysMessage(user.name + " 退出了房间。");
			gameRoomWorld.userList.listCountChanged();
			gameRoomWorld.checkStartButton();
		}

		private function onRoomMasterChanged(user:User):void
		{
			gameRoomWorld.messagePanel.appendSysMessage(user.name + " 成为了房间管理员。");
			gameRoomWorld.userList.updateItem(user);
			gameRoomWorld.checkStartButton();
		}

		private function onGoldGameStart():void
		{
			gameRoomWorld.gameStart();
		}

		private function onUserGetACard(cardType:int):void
		{
			gameRoomWorld.cardGroup.addCard(CardUtil.parseCardByType(cardType));
		}

		private function onUserSetACard(pack:SetRoadCardResponsePack):void
		{
			var card:RoadCardUI = gameRoomWorld.cardMap.setCardPosition(CardUtil.parseCardByType(pack.id), pack.x, pack.y);
			if (card && pack.toggled)
			{
				card.toggleCard();
			}
		}

		private function onSetToolToUser(pack:SetToolToUserResponsePack):void
		{
			var userSeat:UserSeat = gameRoomWorld.getSeatById(pack.targetUserId);
			if (userSeat)
			{
				var toolCard:ToolCard = CardUtil.parseCardByType(pack.cardId) as ToolCard;
				if (toolCard && userSeat.canApplyToolCard(toolCard))
				{
					userSeat.applyToolCard(toolCard);
				}
			}
		}

		private function onChangeCurrentTurn():void
		{
			gameRoomWorld.setCurrentTurnUser(Me.Instace.currentTurn);
		}

		private function onGoldGameComplete(pack:GoldCompleteResponsePack):void
		{
			var user:User = ProxyHelper.getUser(pack.userId);
			if (user)
			{
				var card:EndCardUI = gameRoomWorld.cardMap.getEndCard(pack.direct);
				if (card)
				{
					gameRoomWorld.messagePanel.appendSysMessage(user.name + " 赢得了比赛");
					card.endCard.isknown = true;
					card.color = 0xffdf0a;
				}
			}
		}

		private function onDumpSee(direct:int, isGold:Boolean = false):void
		{
			var card:EndCardUI = gameRoomWorld.cardMap.getEndCard(direct);
			if (card)
			{
				card.endCard.isknown = true;
				if (isGold)
				{
					card.color = 0xdce22d;
				}
				else
				{
					card.color = 0xaaaaaa;
				}
			}
		}

		private function onRemoveRoadCard(point:Point):void
		{
			gameRoomWorld.cardMap.removeCard(point.x, point.y);
		}

		override public function handleNotification(note:INotification):void
		{
			switch (note.getName())
			{
				case AppConstrants.EXIT_ROOM_SUCCESS:
					onExitRoomSuccess();
					break;
				case AppConstrants.EXIT_ROOM_FAIL:
					onExitRoomFail();
					break;
				case AppConstrants.RECEIVE_ROOM_MESSAGE:
					onReceiveLobbyMessage(note.getBody() as TalkVo);
					break;
				case AppConstrants.USER_ENTER_ROOM:
					onUserEnterRoom(note.getBody() as User);
					break;
				case AppConstrants.USER_EXIT_GAME_ROOM:
					onUserExitRoom(note.getBody() as User);
					break;
				case AppConstrants.ROOM_MASTER_CHANGED:
					onRoomMasterChanged(note.getBody() as User);
					break;
				case AppConstrants.GET_READY_FAIL:
					onGetReadyFail();
					break;
				case AppConstrants.USER_GET_READY:
					onUserGetReady(note.getBody() as User);
					break;
				case AppConstrants.GOLD_GAME_START:
					onGoldGameStart();
					break;
				case AppConstrants.SEND_USER_A_CARD:
					onUserGetACard(note.getBody() as int);
					break;
				case AppConstrants.SET_A_ROAD_CARD:
					onUserSetACard(note.getBody() as SetRoadCardResponsePack);
					break;
				case AppConstrants.SET_TOOL_TO_USER:
					onSetToolToUser(note.getBody() as SetToolToUserResponsePack);
					break;
				case AppConstrants.CHANGE_CURRENT_TURN:
					onChangeCurrentTurn();
					break;
				case AppConstrants.GOLD_COMPELETE:
					onGoldGameComplete(note.getBody() as GoldCompleteResponsePack);
					break;
				case AppConstrants.DUMP_SEE:
					onDumpSee(note.getBody() as int);
					break;
				case AppConstrants.GOLD_SEE:
					onDumpSee(note.getBody() as int, true);
					break;
				case AppConstrants.REMOVE_ROAD_CARD:
					onRemoveRoadCard(note.getBody() as Point);
					break;
			}
		}

		override public function listNotificationInterests():Array
		{
			return [
				AppConstrants.EXIT_ROOM_SUCCESS,
				AppConstrants.EXIT_ROOM_FAIL,
				AppConstrants.RECEIVE_ROOM_MESSAGE,
				AppConstrants.USER_ENTER_ROOM,
				AppConstrants.USER_EXIT_GAME_ROOM,
				AppConstrants.ROOM_MASTER_CHANGED,
				AppConstrants.GET_READY_FAIL,
				AppConstrants.USER_GET_READY,
				AppConstrants.GOLD_GAME_START,
				AppConstrants.SEND_USER_A_CARD,
				AppConstrants.SET_A_ROAD_CARD,
				AppConstrants.SET_TOOL_TO_USER,
				AppConstrants.CHANGE_CURRENT_TURN,
				AppConstrants.GOLD_COMPELETE,
				AppConstrants.DUMP_SEE,
				AppConstrants.GOLD_SEE,
				AppConstrants.REMOVE_ROAD_CARD
				];
		}
	}
}
